import { _decorator, Animation, animation, Component, Node, Vec3,EventTarget, tween, AudioClip, AudioSource } from 'cc';
import { Actor } from './Actor';
import { ResourceManager } from '../PlayableFramework/Tools/Manager/ResourceManager';
import { Sprite } from '../../extensions/plugin-import-2x/creator/components/Sprite';
import { Repair } from './Repair';
const { ccclass, property } = _decorator;

@ccclass('Room')
export class Room extends Component {

    
    @property(Node)
    public front: Node = null!; // front 节点

    @property(Node)
    public back: Node = null!; // back 节点

    @property
    public level: number = 0; // 配置显示的层级，默认值为 0


    @property(Node)
    public seatRoot:Node;

    public seatNodeList : Node[][] = [];
    public seatActorList : Actor[] = [];

    private eventTarget:EventTarget;
    
    
    @property(Node)
    public entry: Node;

    @property(Node)
    public exit: Node;

    @property(Node)
    public entryParent:Node;
    

    start() {
        for (let i = 0; i < this.seatRoot.children.length; i++) {
            this.seatNodeList[i] = [];
            for (let j = 0; j < this.seatRoot.children[i].children.length; j++) {
                this.seatNodeList[i][j] = (this.seatRoot.children[i].children[j]);
            }
        }
    }

    public bindEventTarget(target:EventTarget){
        this.eventTarget = target;
    }

    public addLevel()
    {
        this.setLevel(this.level+1);
    }

    public hideLevel()
    {
        for (let i = 0; i < this.seatRoot.children.length; i++) {
            this.seatRoot.children[i].active = i == 0;
        }
        this.updateChilrenByLevel();
    }
    /**
     * 设置显示的层级
     * @param level 显示的层级（0-based）
     */
    public setLevel(level: number) {
        if(level < this.level)
        {
            console.error("不能反向升级目前");
        }
        if(level == this.level)return;
        this.level = level;
        {
            for (let i = 0; i < this.seatRoot.children.length; i++) {
                this.seatRoot.children[i].active = i == this.level;
            }

            let preSeatDataList:Actor[]=[]
            //把之前level的actor全挪到新level里
            if(this.level > 1)
            {
                for (let i = 0; i < this.seatActorList.length; i++) {
                    preSeatDataList.push(this.seatActorList[i]);
                }
            }

            var count = 0;
            var currentSeatNodeList = this.seatNodeList[this.level];
            if(currentSeatNodeList != null){
                for (let i = 0; i < currentSeatNodeList.length; i++) {
                    this.seatActorList[i] = null;
                    if(preSeatDataList[i] != null)
                    {
                        this.seatActorList[i] = preSeatDataList[i];
                        this.seatActorList[i].seatIndex = i;
                        count++;
                    }
                }
                console.log("该room当前等级为:" + this.level + "  容量为:"+ count +"/" + currentSeatNodeList.length);
            }
        }
        if(this.level > 1){
            var effect = ResourceManager.spawn("UpgradeEffect",ResourceManager.getPoolNode("UpgradeEffectParent"));
            effect.node.worldPosition = this.node.worldPosition;
            this.upgradeAnim();
            
        }
        this.updateChilrenByLevel();
    }

    private upgradeAnim(){
        var a = 1.3;
        tween(this.front).to(0.1,{worldScale:new Vec3(a,a,a)}).call(()=>{
            var b = 1;
            tween(this.front).to(0.1,{worldScale:new Vec3(b,b,b)}).start().call(()=>{

            }).start();
        }).start();
        tween(this.back).to(0.1,{worldScale:new Vec3(a,a,a)}).call(()=>{
            var b = 1;
            tween(this.back).to(0.1,{worldScale:new Vec3(b,b,b)}).call(()=>{
                

            }).start();
        }).start();
    }

    /**
     * 更新显示的子物体层级
     */
    private updateChilrenByLevel() {

        var children = this.back.children;
        for (let i = 0; i < children.length; i++) {
            children[i].active = (i === this.level);
        }

        //this.front.setParent(ResourceManager.getPoolNode("RoomFrontParent"),true);
        var children = this.front.children;
        for (let i = 0; i < children.length; i++) {
            children[i].active = (i === this.level);
        }
    }


    public addActor(actor : Actor,roomIndex:number):boolean
    {
        var currentSeatNodeList = this.seatNodeList[this.level];

        var addSuccess = false;
        for (let i = 0; i < currentSeatNodeList.length; i++) {
            if(this.seatActorList[i] == null)
            {
                //设置actor的状态
                {
                    this.seatActorList[i] = actor;
                    this.seatActorList[i].seatIndex = i;
                    this.seatActorList[i].roomIndex = roomIndex;
                }

                actor.node.setParent(ResourceManager.getPoolNode("FixingParent"),true);



                actor.moveToRoom(()=>{

                    actor.entryRoom(()=>{
                        //console.log("正常流程：来到房间门口");
                        actor.node.setParent(this.entryParent,true);
                        actor.moveToRoomSeat(()=>{
                            //console.log("正常流程：来到位置上");
    
                            var fixParent = this.seatNodeList[this.level][actor.seatIndex].getChildByName("修车中")
                            fixParent.active = true;
                            fixParent.children[0].active = false;
                            actor.walkBike.worldPosition = fixParent.worldPosition.clone();
                            var anim = fixParent.getComponent(Animation);
                            anim.clips[0].wrapMode = 2;
                            anim.play("fix");
    
                            var repair = this.seatNodeList[this.level][actor.seatIndex].getChildByName("修车工").getComponent(Repair);
                            repair.anim.play("fix");
    
                            actor.rideBike.active = false;
                            //actor.walkBike.active = false;
    
                            actor.anim.play("idle");
                            actor.fixBike(()=>{
                                //console.log("正常流程：修完了");
                                repair.anim.play("idle");
                                fixParent.active = false;
    
                                actor.rideBike.active = true;
                                actor.walkBike.active = false;
                                
                                actor.mover.movementParameter = 300;

                                actor.moveToRoomExit(()=>{
                                    //console.log("正常流程：出门咯");
    
                                    actor.rideBike.active = true;
                                    actor.walkBike.active = false;
    
                                    if(roomIndex == 0 || roomIndex == 1){
                                        actor.node.setParent(ResourceManager.getPoolNode("road1"),true);
                                    }
                                    else
                                    {
                                        actor.node.setParent(ResourceManager.getPoolNode("road2"),true);
                                    }
    
                                    actor.moveToExit(()=>{
                                        //console.log("正常流程：结束咯");
                                        ResourceManager.despawn(actor,null);
                                    });
                                });
                                //把Actor状态清除
                                {
                                    this.seatActorList[actor.seatIndex] = null;
                                    actor.seatIndex = -1;
                                    this.eventTarget.emit('addMoney',{money : 20,pos : actor.node.worldPosition});
                                }
                            });
                        });
                    });
                },(index)=>{
                    var pathRoot = actor.mover.pathRoot.children[index];
                    if(pathRoot.name == "haha"){
                        actor.node.setParent(ResourceManager.getPoolNode("road2"),true);
                    }

                    if(pathRoot.name == "hehe"){
                        actor.node.setParent(ResourceManager.getPoolNode("road1"),true);
                    }
                });


                addSuccess = true;
                break;
            }
        }

        if(addSuccess)console.log("该room当前等级为:" + this.level + "  容量为:"+ (currentSeatNodeList.length - this.getFreeCount()) +"/" + currentSeatNodeList.length);

        return addSuccess;
    }
    

    private getFreeCount():number
    {
        var count = 0;
        for (let i = 0; i < this.seatActorList.length; i++) {
            if(this.seatActorList[i] == null)
            {
                count++;
            }
        }
        return count;
    }

    public getSeat(index:number):Node{
        var currentSeatNodeList = this.seatNodeList[this.level];
        return currentSeatNodeList[index];
    }

    public getExit():Node{
        return this.exit.children[this.level];
    }


}

